/**
 * 首页脚本 - 文本摘要功能
 */

class SummarizerApp {
    constructor() {
        // 输入元素
        this.inputText = document.getElementById('input-text');
        this.inputFile = document.getElementById('input-file');
        this.fileInfo = document.getElementById('file-info');
        this.summaryRatio = document.getElementById('summary-ratio');
        this.ratioValue = document.getElementById('ratio-value');
        
        // 按钮
        this.summarizeBtn = document.getElementById('summarize-btn');
        this.clearBtn = document.getElementById('clear-btn');
        this.copyBtn = document.getElementById('copy-btn');
        this.saveBtn = document.getElementById('save-btn');
        
        // 结果区域
        this.resultSection = document.getElementById('result-section');
        this.summaryContent = document.getElementById('summary-content');
        this.keywordsContent = document.getElementById('keywords-content');
        this.originalContent = document.getElementById('original-content');
        
        // 当前文件
        this.currentFile = null;
        
        this.init();
    }
    
    // 初始化
    init() {
        // 绑定摘要比例滑块事件
        if (this.summaryRatio && this.ratioValue) {
            this.summaryRatio.addEventListener('input', () => {
                this.ratioValue.textContent = `${this.summaryRatio.value}%`;
            });
        }
        
        // 绑定文件上传事件
        if (this.inputFile && this.fileInfo) {
            this.inputFile.addEventListener('change', (e) => this.handleFileSelect(e));
            
            // 拖放文件
            const fileUploadLabel = document.querySelector('.file-upload-label');
            if (fileUploadLabel) {
                fileUploadLabel.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    fileUploadLabel.classList.add('dragover');
                });
                
                fileUploadLabel.addEventListener('dragleave', () => {
                    fileUploadLabel.classList.remove('dragover');
                });
                
                fileUploadLabel.addEventListener('drop', (e) => {
                    e.preventDefault();
                    fileUploadLabel.classList.remove('dragover');
                    
                    if (e.dataTransfer.files.length > 0) {
                        this.inputFile.files = e.dataTransfer.files;
                        this.handleFileSelect({ target: this.inputFile });
                    }
                });
            }
        }
        
        // 绑定生成摘要按钮事件
        if (this.summarizeBtn) {
            this.summarizeBtn.addEventListener('click', () => this.generateSummary());
        }
        
        // 绑定清空按钮事件
        if (this.clearBtn) {
            this.clearBtn.addEventListener('click', () => this.clearAll());
        }
        
        // 绑定复制按钮事件
        if (this.copyBtn) {
            this.copyBtn.addEventListener('click', () => this.copyResult());
        }
        
        // 绑定保存按钮事件
        if (this.saveBtn) {
            this.saveBtn.addEventListener('click', () => this.saveResult());
        }
    }
    
    // 处理文件选择
    handleFileSelect(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        this.currentFile = file;
        
        // 显示文件信息
        if (this.fileInfo) {
            this.fileInfo.innerHTML = `
                <div class="file-info-item">
                    <span class="file-name">${file.name}</span>
                    <span class="file-size">${utils.formatFileSize(file.size)}</span>
                </div>
            `;
        }
        
        // 切换到文件标签
        const fileTabBtn = document.querySelector('.tab-btn[data-tab="file"]');
        if (fileTabBtn) {
            fileTabBtn.click();
        }
    }
    
    // 生成摘要
    async generateSummary() {
        try {
            // 验证输入
            const activeTab = document.querySelector('.tab-btn.active').getAttribute('data-tab');
            let text = '';
            let isFile = false;
            
            if (activeTab === 'text') {
                text = this.inputText.value.trim();
                if (!text) {
                    notificationSystem.show('请输入要摘要的文本', 'warning');
                    return;
                }
            } else if (activeTab === 'file') {
                if (!this.currentFile) {
                    notificationSystem.show('请选择要摘要的文件', 'warning');
                    return;
                }
                isFile = true;
            }
            
            // 获取摘要比例
            const ratio = parseInt(this.summaryRatio.value) / 100;
            
            // 显示加载状态
            loadingManager.show();
            
            let result;
            if (isFile) {
                // 文件摘要
                result = await apiService.summarizeFile(this.currentFile, ratio);
            } else {
                // 文本摘要
                result = await apiService.summarize(text, ratio);
            }
            
            // 显示结果
            this.displayResult(result);
            
        } catch (error) {
            notificationSystem.show(error.message, 'error');
        } finally {
            loadingManager.hide();
        }
    }
    
    // 显示结果
    displayResult(result) {
        // 显示结果区域
        this.resultSection.classList.add('show');
        
        // 更新摘要内容
        if (this.summaryContent) {
            this.summaryContent.innerHTML = `<p>${result.摘要}</p>`;
        }
        
        // 更新关键词内容
        if (this.keywordsContent) {
            this.keywordsContent.innerHTML = result.关键词
                .map(word => `<span class="keyword-tag">${word}</span>`)
                .join('');
        }
        
        // 更新原文内容
        if (this.originalContent) {
            this.originalContent.innerHTML = `<p>${result.原文}</p>`;
        }
        
        // 滚动到结果区域
        this.resultSection.scrollIntoView({ behavior: 'smooth' });
    }
    
    // 清空所有
    clearAll() {
        // 清空文本输入
        if (this.inputText) {
            this.inputText.value = '';
        }
        
        // 清空文件输入
        if (this.inputFile) {
            this.inputFile.value = '';
        }
        
        // 清空文件信息
        if (this.fileInfo) {
            this.fileInfo.innerHTML = '';
        }
        
        // 重置当前文件
        this.currentFile = null;
        
        // 隐藏结果区域
        this.resultSection.classList.remove('show');
        
        // 清空结果内容
        if (this.summaryContent) {
            this.summaryContent.innerHTML = '<p class="placeholder">摘要将显示在这里...</p>';
        }
        
        if (this.keywordsContent) {
            this.keywordsContent.innerHTML = '<p class="placeholder">关键词将显示在这里...</p>';
        }
        
        if (this.originalContent) {
            this.originalContent.innerHTML = '<p class="placeholder">原文将显示在这里...</p>';
        }
    }
    
    // 复制结果
    copyResult() {
        const activeTab = document.querySelector('.result-tabs .tab-btn.active').getAttribute('data-tab');
        let content = '';
        
        if (activeTab === 'summary') {
            content = this.summaryContent.textContent;
        } else if (activeTab === 'keywords') {
            content = Array.from(this.keywordsContent.querySelectorAll('.keyword-tag'))
                .map(tag => tag.textContent)
                .join(', ');
        } else if (activeTab === 'original') {
            content = this.originalContent.textContent;
        }
        
        if (!content) {
            notificationSystem.show('没有可复制的内容', 'warning');
            return;
        }
        
        utils.copyToClipboard(content)
            .then(() => {
                notificationSystem.show('已复制到剪贴板', 'success');
            })
            .catch(() => {
                notificationSystem.show('复制失败', 'error');
            });
    }
    
    // 保存结果
    async saveResult() {
        try {
            loadingManager.show();
            
            // 获取当前结果
            const summary = this.summaryContent.textContent;
            const keywords = Array.from(this.keywordsContent.querySelectorAll('.keyword-tag'))
                .map(tag => tag.textContent);
            const original = this.originalContent.textContent;
            
            // 获取摘要比例
            const ratio = parseInt(this.summaryRatio.value) / 100;
            
            // 构建保存数据
            const saveData = {
                摘要: summary,
                关键词: keywords,
                原文: original,
                比例: ratio,
                文件名: this.currentFile ? this.currentFile.name : null,
                日期: new Date().toISOString()
            };
            
            // 调用API保存
            await apiService.request('/api/history/save', 'POST', saveData);
            
            notificationSystem.show('结果已保存', 'success');
            
        } catch (error) {
            notificationSystem.show('保存失败: ' + error.message, 'error');
        } finally {
            loadingManager.hide();
        }
    }
}

// 初始化摘要应用
document.addEventListener('DOMContentLoaded', () => {
    new SummarizerApp();
});